﻿using System;
using System.Collections.Generic;
using CardLogistics.Web.Components;
using CardLogistics.Model.CardRecovery;
using System.Data;
using System.Text;
using CardLogistics.DAL.Purchase;
using CardLogistics.DAL.CardRecovery;

namespace CardLogistics.Web.MainPage.CardRecovery.ReturnBadCard
{
    public partial class AddEdit : BasePage
    {
        #region 变量
        #endregion
        private static readonly CardLogistics.DAL.CardRecovery.CARDRECOVERY_RETURNCARDData DAL = new CARDRECOVERY_RETURNCARDData();
        private static readonly CardLogistics.DAL.CardRecovery.CARDRECOVERY_RETURNCARD_DETAILData DetailedDAL = new CARDRECOVERY_RETURNCARD_DETAILData();
        //白卡验收入库明细
        private static readonly CardLogistics.DAL.CardArrival.Storage_Detailed_CardData StDetDAL = new CardLogistics.DAL.CardArrival.Storage_Detailed_CardData();
        string FileValue = ""; //卡片退货明细字段
        /// <summary>
        /// 盒号集合
        /// </summary>
        protected Dictionary<string, string> CardNOList = new Dictionary<string, string>();
        /// <summary>
        /// 增加的行
        /// </summary>
        protected StringBuilder AddTr = new StringBuilder();
        public string TitleName
        {
            get;
            set;
        }
        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            TitleName = GetStatusInfo(0, "卡片退货");
            if (!IsPostBack)
            {
                RETURNDATA.Value = DateTime.Now.ToString("yyyy-MM-dd");//退货日期
                ATTN.Value = LoggedUser.USERFULLNAME;//经办人默认为当前登录用户
                InitControl(sender, e);
            }
        }
        #endregion

        #region 得到一个对象实体
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public void InitControl(object sender, EventArgs e)
        {
            TitleName = GetStatusInfo(0, "卡片退货");
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    CARDRECOVERY_RETURNCARD rData = DAL.GetModel(_key);
                    SetWebControls(this.Page, rData);
                    hf_ConId.Value = rData.CONID;//合同单明细批次ID
                    TypeValue_Click(sender, e);//绑定盒号信息
                    GetConDetInfo(rData.CONID);//根据选择的合同明细获取详细信息
                    //根据白卡出库单查询出库明细
                    DataTable dt = DetailedDAL.GetInfoByReturnId(_key);
                    string strId = "";
                    int editCardNum = 0;
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            strId += dr["boxno"].ToString() + "|" + dr["cardno"].ToString() + "|" + dr["startno"].ToString() + "|" + dr["endno"].ToString() + "|" +
                                     dr["deservednumber"].ToString() + "|" + dr["actualnumber"].ToString() + "|" + dr["missingcardno"].ToString() + ";";

                            //获取编辑前的卡片数量
                            editCardNum += (Convert.ToInt32(dr["EndNo"].ToString()) - Convert.ToInt32(dr["StartNo"].ToString()) + 1);

                        }
                        hf_CheckId.Value = strId.TrimEnd(';');
                        hfEditSumCard.Value = editCardNum.ToString(); //获取编辑前的卡片数量
                    }
                    btn_Add.Visible = btn_Submit.Visible = false;
                    if (rData.ISSUBMIT == 0 || rData.ISSUBMIT == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    TitleName = GetStatusInfo(int.Parse(rData.ISSUBMIT.ToString()), "卡片退货");
                }
            }
            else
            {
                RETURNCARDNO.Value = GetBillNumber("卡片退货");
            }
        }
        #endregion

        #region 保存按钮事件
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                ShowMegByResult(result, 0);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 保存并提交
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                ShowMegByResult(result, 1);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 提示信息
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="result"></param>
        private void ShowMegByResult(string result, int issubmit)
        {
            if (result.Split(',')[0] == "ok")
            {
                if (issubmit == 1)
                {
                    InsertAppInfo(14, result.Split(',')[1]); //14:卡片退货
                    InsertLog("保存并提交卡片退货信息,退货单号:" + RETURNCARDNO.Value);
                }
                else
                    InsertLog("保存卡片退货信息,退货单号:" + RETURNCARDNO.Value);
                ReturnListInfo();
            }
            else
            {
                ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
            }
        }
        #endregion

        #region 得到对象
        /// <summary>
        /// 卡片退货信息
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            string result = string.Empty;
            CARDRECOVERY_RETURNCARD model = new CARDRECOVERY_RETURNCARD();
            model = GetWebControls<CARDRECOVERY_RETURNCARD>(this.Page);
            model.LASTUPDATEUSER = LoggedUser.ID;//最后修改人
            model.LASTUPDATEDATE = DateTime.Now; //最后修改时间
            model.CONID = hf_ConId.Value; //合同单ID
            model.ISSUBMIT = issubmit;//0 未提交 1 待审核 2 审核中 3 驳回 4 审核不通过 5审核通过
            FileValue = hf_CheckId.Value; //卡片退货明细字段
            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model, FileValue);
            }
            else
            {
                result = DAL.Add(model, FileValue);
                if (result.Split(',')[0] == "ok")
                {
                    ChgBillNumber("卡片退货");
                }
            }
            return result;
        }
        #endregion

        #region 根据选择的合同明细获取详细信息
        /// <summary>
        /// 通过合同ID获取详细信息事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void TypeValue_Click(object sender, EventArgs e)
        {
            hf_CheckId.Value = "";
            string conId = hf_ConId.Value;
            GetConDetInfo(conId);//根据选择的合同明细获取详细信息
            DataTable dtStDet = StDetDAL.GetInInfoByConID(conId);//根据合同批次明细ID查询该合同的入库盒号信息
            if (dtStDet != null && dtStDet.Rows.Count > 0)
            {
                foreach (DataRow dr in dtStDet.Rows)
                {
                    //箱号|开始卡号|结束卡号|应有数量|实际数量|缺失卡号
                    string idStr = dr["boxno"].ToString() + "|" + dr["startno"].ToString() + "|" + dr["endno"].ToString() + "|" + dr["DESERVEDNUMBER"].ToString() + "|" + dr["ACTUALNUMBER"].ToString() + "|" + dr["missingcardno"].ToString();
                    CardNOList.Add(idStr, dr["cardno"].ToString().Trim());
                }
                if (dtStDet.Rows.Count > 10)
                {
                    for (int i = 11; i <= dtStDet.Rows.Count; i++)
                    {
                        AddTr.Append("<tr><td>" + i + "</td>");
                        AddTr.Append("<td><input name='BoxNo' type='text' class='dfinput'/>");
                        AddTr.Append("</td><td><select name='CardNo' onchange='selCardNoInfo(this)'>");
                        AddTr.Append("<option value='0'></option>");
                        foreach (var cno in CardNOList)
                        {
                            AddTr.Append("<option value='" + cno.Key + "'>" + cno.Value + "</option>");
                        }
                        AddTr.Append("</select></td>");
                        AddTr.Append("<td><input name='StartNo' type='text' class='dfinput' /> </td>");
                        AddTr.Append("<td><input name='EndNo' type='text' class='dfinput' /></td>");
                        AddTr.Append("<td><input name='DueNumbers' type='text' class='dfinput' value='0' /></td>");
                        AddTr.Append("<td><input name='ActualNumber' type='text' class='dfinput' value='0' /></td>");
                        AddTr.Append("<td><input name='MissingCardNo' type='text' class='dfinput' /></td>");
                        AddTr.Append("<td>&nbsp;</td></tr>");
                    }
                }
            }
        }

        /// <summary>
        /// 根据选择的合同明细获取详细信息
        /// </summary>
        /// <param name="conId">合同明细ID</param>
        private void GetConDetInfo(string conId)
        {
            DataTable dt = new Purchase_Contract_detailData().GetInfoById(conId);
            if (dt.Rows.Count > 0)
            {
                lblConInfo.Text = "供应商:" + dt.Rows[0]["suppliersname"].ToString();
                lblConInfo.Text += " 芯片类型:" + dt.Rows[0]["typename"].ToString();
                lblConInfo.Text += " 单价:" + decimal.Parse(dt.Rows[0]["PRICE"].ToString()).ToString("0.00") + "元/张";
                lblConInfo.Text += " 数量:" + dt.Rows[0]["CARDAMOUNT"].ToString() + "张";
                lblConInfo.Text += " 备品数量:" + dt.Rows[0]["SPAREPARTS"].ToString() + "张";
                lblConInfo.Text += " 赠品数量:" + dt.Rows[0]["PREMIUMS"].ToString() + "张";
                lblConInfo.Text += " 数量合计:" + dt.Rows[0]["allTotal"].ToString() + "张";
                lblConInfo.Text += " 金额合计:" + (decimal.Parse(dt.Rows[0]["PRICE"].ToString()) * decimal.Parse(dt.Rows[0]["CARDAMOUNT"].ToString())).ToString("0.00") + "元";
                if (PConNo.Value.Trim().Equals(""))
                    PConNo.Value = dt.Rows[0]["batchno"].ToString();
            }
        }
        #endregion
    }
}